﻿using System.IO;
using System;

namespace Library.Gsm.AtCommands {
  public abstract class BaseAtCommand : IAtCommand {
    public const string Cr = "\r";
    protected virtual string Ok {
      get { return "OK"; }
    }


    public virtual int Instance {
      get { return 1; }
    }


    public string UserCommandText { get; set; }

    public virtual string AtCommandText {
      get { return UserCommandText + Cr; }
    }

    public virtual OneLineStringCollection ParseResponse(string response, IGsmCommand gsmCommand) {
      return ReadToEndOk(response);
    }

   

    public virtual void CreateCommandText(params object[] parameter) {
      UserCommandText = GetCommandText(parameter);
    }

    protected abstract string GetCommandText(params object[] parameter);

    protected virtual bool AddLine(OneLineStringCollection lines, string line) {
      if (String.IsNullOrEmpty(line)) return false;
      if (line == UserCommandText) return false;
      lines.Add(line.Trim());
      return true;
    }

    protected OneLineStringCollection ReadToEndOk(string reponse) {
      var result = new OneLineStringCollection();
      var reader = new StringReader(reponse);
      var line = reader.ReadLine();
      while (line != null) {
        if (line == Ok) {
          var nextLine = reader.ReadLine();
          if (nextLine == null)
            return result;
          AddLine(result, line);

          line = nextLine;
        } else {
          AddLine(result, line);
          line = reader.ReadLine();
        }
      }

      return result;
    }
  }
}
